<?php
declare(strict_types = 1);

namespace app\logic;

use app\ArrayToolkit;
use app\logic\BaseLogic;
use think\facade\Db;

class Setting extends BaseLogic
{
    public function createSetting(array $fields)
    {
        $fields = $this->filterSettingFields($fields);

        if (empty($fields)) {
            return null;
        }

        if (!ArrayToolkit::requireds($fields, ['name', 'value'])) {
            $this->throwHttpException(500, '缺少必要参数');
        }

        if (!empty($this->getSettingByName($fields['name']))) {
            $this->throwHttpException(500, '该数据已存在');
        }
        $this->getSettingModel()->save($fields);
        return $this->getSettingByName($fields['name']);
    }

    public function updateSetting($id, array $fields)
    {
        $setting = $this->getSetting($id);

        if (empty($setting)) {
            $this->throwHttpException(500, '数据不存在');
        }
        $fields = $this->filterSettingFields($fields);

        if (empty($fields)) {
            return null;
        }

        if ($fields['name'] != $setting['name'] && !empty($this->getSettingByName($fields['name']))) {
            $this->throwHttpException(500, '该模版已存在');
        }

        $this->getSettingModel()->save($fields);
        return $this->getSetting($id);
    }

    public function deleteSetting($id)
    {
        $setting = $this->getSettingModel($id);

        if (empty($setting)) {
            $this->throwHttpException(500, '数据不存在');
        }

        return $this->getSettingModel()->delete($id);
    }

    public function getSetting($id)
    {
        if (empty($id)) {
            return [];
        }
        return $this->getSettingModel()->getById($id);
    }

    public function findSettingByIds(array $ids)
    {
        if (empty($ids)) {
            return [];
        }
        return $this->getSettingModel()->findByIds($ids);
    }

    public function getSettingByName($name)
    {
        if (empty($name)) {
            return [];
        }
        return $this->getSettingModel()->getByName($name);
    }

    public function getByFields($field, $value)
    {
        return $this->getSettingModel()->getByFields($field, $value);
    }

    protected function filterSettingFields(array $fields)
    {
        $fields = ArrayToolkit::parts($fields, [
            'name',
            'value',
            'update_time',
            'created_time',
        ]);

        return $fields;
    }

    /**
     * @return \app\model\Setting
     */
    protected function getSettingModel()
    {
        return $this->getModel('Setting');
    }
}
